package xyz.poke.business.tool.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import xyz.poke.business.tool.common.ErrorCode;
import xyz.poke.business.tool.constants.CommonConstants;
import xyz.poke.business.tool.dto.UserDTO;
import xyz.poke.business.tool.enums.UserRoleEnum;
import xyz.poke.business.tool.exception.BusinessException;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

import static xyz.poke.business.tool.common.ErrorCode.UNAUTHORIZED;

/**
 * @author 迫壳
 * @date 2024/3/23 17:07
 */
public class UserUtils {

    /**
     * 获取当前请求的登录人信息
     **/
    public static UserDTO getCurrentUser() {
        //从请求头中获取token
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(attributes) || Objects.isNull(attributes.getRequest())) {
            return null;
        }
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader(CommonConstants.TOKEN_COOKIE_KEY);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        RedisUtils redisUtils = SpringContextUtils.getContext().getBean(RedisUtils.class);
        Object user = redisUtils.get(token);
        if (Objects.isNull(user)) {
            return null;
        }
        return JSON.parseObject((String) user, UserDTO.class);
    }

    /**
     * 校验用户的角色
     **/
    public static void validUserRole(UserDTO user, List<UserRoleEnum> userRoleEnums) {
        if (CollectionUtils.isEmpty(userRoleEnums)) {
            return;
        }
        if (Objects.isNull(user) || Objects.isNull(user.getRoleIds())) {
            throw new BusinessException(UNAUTHORIZED.getCode(), "用户信息有问题，请重新登录");
        }
        for (UserRoleEnum userRoleEnum : userRoleEnums) {
            if (!user.getRoleIds().contains(userRoleEnum.getId())) {
                throw new BusinessException(ErrorCode.FORBIDDEN);
            }
        }
    }

}
